package top.gbiot.redis.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.gbiot.common.core.domain.AjaxResult;
import top.gbiot.common.utils.ServletUtils;
import top.gbiot.redis.service.RedisService;
import top.gbiot.redis.util.RedisUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Controller
@RequestMapping("/monitor/redis")
public class RedisController {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private RedisService redisService;

    private String prefix = "monitor/redis";

    @Cacheable(cacheNames = "users",keyGenerator = "myKeyGenerator")
    @GetMapping("/{userId}")
    @ResponseBody
    public AjaxResult test(@PathVariable("userId")Long userId){
        return AjaxResult.success("success!"+userId);
    }

    @GetMapping("/key/{key}")
    @ResponseBody
    public AjaxResult findKeysForPage(@PathVariable("key")String key){
        return AjaxResult.success(redisUtils.get1(key));
    }

    /**
     * 跳转页面
     * @return
     */
    @RequestMapping(value={"","/"})
    public String index(){
        return prefix+"/list";
    }

    @RequestMapping("/viewCacheInfoByKey")
    public String viewCacheInfo(String key, Model model){

        if(key.contains("$")){
            key=key.replace("$","#") ;
        }
        Map<String,Object> info= redisService.viewCacheInfoByKey(key);
        model.addAttribute("info",info);
        return prefix+"/viewInfo";
    }

    /**
     * redis缓存信息列表
     * @param req
     * @return
     */
    @ResponseBody
    @RequestMapping("/list")
    public Object list(HttpServletRequest req){
        Map map= ServletUtils.getMap(req);
        return redisService.listPg(map);
    }

    /**
     * 清除缓存信息
     * @param key
     * @return
     */
    @ResponseBody
    @RequestMapping("/removeCacheByKey")
    public Object removeCacheByKey(String key){
        if(key.contains("$")){
            key=key.replace("$","#") ;
        }
        return redisService.removeCacheByKey(key);
    }

}
